#Title: Switch Statement

You should use the Switch statement if you want to select one of many blocks of code to be executed.

Syntax

switch (expression)
{
case label1:
  code to be executed if expression = label1
  break    
case label2:
  code to be executed if expression = label2
  break
default:
  code to be executed
  if expression is different 
  from both label1 and label2
}

This is how it works: First we have a single expression (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically.

Example

<script type="text/javascript">
//You will receive a different greeting based
//on what day it is. Note that Sunday=0,
//Monday=1, Tuesday=2, etc.
var d=new Date()
theDay=d.getDay()
switch (theDay)
{
case 5:
  document.write("Finally Friday")
  break
case 6:
  document.write("Super Saturday")
  break
case 0:
  document.write("Sleepy Sunday")
  break
default:
  document.write("I'm looking forward to this weekend!")
}
</script>

#Title: Conditional Statements
#Element: 171: Conditional Statements